/*
 * Copyright © Jack魏 2022 - 2022, All Rights Reserved.
 */

package com.jack.thread.t02;

/**
 * 中断异常测试
 *
 * @author Jack魏
 * @since 2022/11/19 11:31
 */
public class StopInterruptException {
    /**
     * 测试异常。继承Runnable接口
     */
    private static class MyRunnable implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    System.out.println("While running");
                    // 这里会接受外部的中断请求，然后抛出InterruptedException异常
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // 如果不执行这一句就会一直执行下去while
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
            }
            System.out.println("Interrupted flag is " + Thread.currentThread().isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread stopThread = new Thread(new MyRunnable());
        stopThread.start();
        Thread.sleep(1000);
        // 发出中断请求
        stopThread.interrupt();
    }
}
